package com.yf.aclient.threads;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.yf.aclient.util.NumberUtil;
/***
 * 
 * 直接通过网络地址下载资源代码。
 * @author yufei
 *
 */
public class DownloadThread extends Thread {
	private  String url;
	private InputStream inputStream;
//	private HttpURLConnection connection;
	private OutputStream outputStream;
	private Handler  handler;
//    private Bitmap bitmap;
	
      double fileLength;
    private String fileName;
	private String  savePath=Environment.getExternalStorageDirectory()+"/Download";
	public DownloadThread(String downloadUrl,Handler handler){
		this.url=downloadUrl;
		this.handler=handler;
	}
	public void  run(){
		try{
			download(url);
		}catch(Exception e){
			e.printStackTrace();
		}
	//	this.stop();
	}
	//android.content.res.Resources$NotFoundException: String resource ID #0x1
	private void download(String downloadUrl){
            /*
	         * 连接到服务器
	         */
	        try {
	      	  fileName=downloadUrl.substring(downloadUrl.lastIndexOf("/")+1, downloadUrl.length());
	        	byte[] data=getImage(downloadUrl);
//	            if(data!=null){      
//	                bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap      
//	              //  imageView.setImageBitmap(bitmap);// display image      
//	            }
	            
//	             URL url=new URL(downloadUrl);
//	             connection=(HttpURLConnection)url.openConnection();
//	             connection.setRequestMethod("GET");
//	             if (connection.getReadTimeout()==5) {
//	                Log.i("---------->", "当前网络有问题");
//	                // return;
//               }
//	             inputStream=connection.getInputStream();
//	             
//	        } catch (MalformedURLException e1) {
//            e1.printStackTrace();
//	        } catch (IOException e) {
//	            e.printStackTrace();
//	        }
//	        /*
//	         * 文件的保存路径如果不存在则新建
//	          */
//
            File file1=new File(savePath);
    	        if (!file1.exists()) {
   	            file1.mkdir();
            }
//    	  saveFile(bitmap,fileName);
          String filePathStr=savePath+"/"+fileName;
	      File file =new File(filePathStr);
          if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
           }  
         }
//		        /*
//		        * 向SD卡中写入文件,用Handle传递线程
//		        */
	        Message message=Message.obtain();
    //    try {
           outputStream=new FileOutputStream(file);
	       byte [] buffer=new byte[1024];
           message.what=0;
           message.obj="开始下载";
           double downloadedLength=0;
	       handler.sendMessage(message);
           double   perSize=0;
           double   reportSize=fileLength*0.1;
           int len = 0;   
          // ByteArrayOutputStream outStream = new ByteArrayOutputStream();
           while( (len=inputStream.read(buffer)) != -1){        	         
        	       perSize+=len;
        	       downloadedLength+=len;
        	       if(perSize>reportSize){
        	    	   perSize=0;
       	        	double p=downloadedLength/fileLength;
       	            Message message2=new Message();
    	            message2.obj="已下载："+NumberUtil.convertNumbertoString(0, p*100)+"%";
    	            message2.what=0;
    	            handler.sendMessage(message2);
        	       }
             //      outStream.write(buffer, 0, len);    
        	       outputStream.write(buffer, 0, len);   
           }   
	            Message message2=new Message();
	            message2.obj="{\"info\":\"下载完成!\",\"fileName\":\""+fileName+"\"}";
	            message2.what=1;
	            handler.sendMessage(message2);
        } catch (Exception e){
//	            // TODO Auto-generated catch block
        	e.printStackTrace();
        	Message message3=new Message();
             message3.obj="下载失败！";
             message3.what=0;
             message3.obj="下载失败！";
            handler.sendMessage(message3);
	            e.printStackTrace();
        }
	}

    /**  
     * Get image from newwork  
     * @param path The path of image  
     * @return byte[]
     * @throws Exception  
     */  
    public byte[] getImage(String path) throws Exception{ 
    	String  fileNm=URLEncoder.encode(fileName);
  	   String fileUrl=path.substring(0,path.lastIndexOf("/"));

    	//path=new String(path.getBytes("utf8"),"utf8");
        URL url = new URL(fileUrl+"/"+fileNm);   
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
        conn.setConnectTimeout(5 * 1000);   
        conn.setRequestProperty("Charset", "utf8");
       // conn.setRequestMethod("POST");
        conn.setRequestMethod("GET");  
        conn.getContentLength();
       // conn.
        InputStream inStream = conn.getInputStream();   
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
        	fileLength=conn.getContentLength();
        	inputStream=inStream;
            return null;   
            //return readStream(inStream);   
        }   
        return null;   
    }   
    /**  
     * Get data from stream 
     * @param inStream  
     * @return byte[]
     * @throws Exception  
     */  
    public static byte[] readStream(InputStream inStream) throws Exception{   
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();   
        byte[] buffer = new byte[1024];   
        int len = 0;   
        while( (len=inStream.read(buffer)) != -1){   
            outStream.write(buffer, 0, len);   
        }   
        outStream.close();   
        inStream.close();   
        return outStream.toByteArray();   
    } 
    /**
     * 保存文件
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        File dirFile = new File(savePath);
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(savePath +"/"+ fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }
}
